﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Facebook;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{
	public class FacebookController : Controller
	{
        private Uri RedirectUri
        {
            get
            {
                var uriBuilder = new UriBuilder(Request.Url);
                uriBuilder.Query = null;
                uriBuilder.Fragment = null;
                uriBuilder.Path = Url.Action("Callback");
                return uriBuilder.Uri;
            }
        }

        public ActionResult Login()
        {
            var fb = new FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id = ConfigurationManager.AppSettings["FB_ClientId"].ToString(),
                client_secret = ConfigurationManager.AppSettings["FB_ClientSecret"].ToString(),
                redirect_uri = RedirectUri.AbsoluteUri,
                response_type = "code",
                //scope = "email first_name last_name"
                scope = "email"
            });

            return Redirect(loginUrl.AbsoluteUri);
        }

        public ActionResult Callback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = ConfigurationManager.AppSettings["FB_ClientId"].ToString(),
                client_secret = ConfigurationManager.AppSettings["FB_ClientSecret"].ToString(),
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so 
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,last_name,email");
            Session["FB_Email"] = me.email;
            Session["FB_FirstName"] = me.first_name;
            Session["FB_LastName"] = me.last_name;

            return RedirectToAction("SubscribeFB", "MailingList");
        }
	}
}
